import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse
} from "@angular/common/http";

import {catchError, tap} from "rxjs/operators";
import {Observable} from "rxjs";
import {LoadingController} from "@ionic/angular";
import { CommonService } from '../service/common.service'
import { StorageService } from './storage.service'
import { Router } from '@angular/router'


@Injectable({
  providedIn: 'root'
})
export class InterceptorService {

  private timeoutMillis = 3000;
  constructor(private loadingView:LoadingController,private common:CommonService,private storage:StorageService,private router:Router
  ) {
  }

  intercept(request: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
    // console.log(111)
    // console.log(request)
    // request.headers.delete('content-security-policy');
    // request.headers.delete('X-Frame-Options');
    // console.log('终于拦截到了。。。1', request.url);
    // debugger
    return next.handle(request)
      .pipe(
        tap(
          event => {
            
            if (event instanceof HttpResponse && event.status === 200) {
              // console.log(event)
              if(event.body.code !== "200" && event.body.code !== "-5"){
                this.common.presentToast(event.body.msg)
                // vent.body.code+","+
                return false
              }
              if(event.body.code == "-5"){
                this.common.presentToast(event.body.msg)
                this.storage.remove('userInfo')
                this.storage.remove('PersonalInfo')
                location.reload()
                // this.router.navigateByUrl('login')
              }

              /**
               * 请求后置处理
               */
              // loadingView.dismiss();
            }
          },
          error => {
            /**
             * 请求异常处理
             */
            // loadingView.dismiss();
            let msg = "请求失败";
            switch (error.status) {
              case 0:
                msg = "请求地址错误";
                break;
              case 400:
                msg = "请求无效，请检查参数类型是否匹配";
                break;
              case 404:
                msg = "请求资源不存在，请检查路径是否正确";
                break;
              default:
                msg = "请求错误，请检查路径是否正确";
                break;
            }
            this.common.presentToast(msg)
            setTimeout(()=>{
              // location.reload()
            },1500)
            
          }
        ),
        catchError((err: any) => {
          // console.log(msg)
          return Observable.throw(err.message);
        })
      );
  }


  // intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  //     // 注入服务器地址
  //     console.log(req)
  //     const authReq = req.clone({
  //       url: (req.url + '&token=ujusaruu19')  //对任意请求的url添加token参数
  //     });
  //     return next.handle(req);
  // }

  
}
